using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using tafei_thingsapi.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.Text;
using tafei_thingsapi.Services;
using tafei_thingsapi.Middleware;
using Microsoft.OpenApi.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;

namespace tafei_thingsapi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "tafei_thingsapi", Version = "v1" });
            });            
            // 配置数据库上下文
            services.AddDbContext<tafei_thingsapiContext>(options =>
                options.UseMySql(Configuration.GetConnectionString("tafei_thingsapiContext"),
                ServerVersion.AutoDetect(Configuration.GetConnectionString("tafei_thingsapiContext"))));
            
            // 添加 JWT 服务
            services.AddScoped<JwtService>();
            
            // 配置 JWT
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer = Configuration["Jwt:Issuer"],
                        ValidAudience = Configuration["Jwt:Audience"],
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                    };
                });

            // 添加 CORS
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll",
                    builder => builder.AllowAnyOrigin()
                                    .AllowAnyMethod()
                                    .AllowAnyHeader());
            });

            // 注册 OneNetService
            services.AddHttpClient<OneNetService>(client =>
            {
                client.Timeout = TimeSpan.FromSeconds(100);
            });
            services.AddSingleton<OneNetService>();

            // 注册华为云视频服务
            services.AddHttpClient<HuaweiVideoService>();
            services.AddScoped<HuaweiVideoService>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "tafei_thingsapi v1"));
            }

            app.UsePathBase("/tafei-things");

            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseStaticFiles();
            
            // 使用 CORS
            app.UseCors("AllowAll");
            
            // 使用认证和授权
            app.UseAuthentication();
            app.UseAuthorization();
            
            // 使用 JWT 中间件
            app.UseMiddleware<JwtMiddleware>();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
